<template>
  <el-dialog
    class="met-dialog"
    title="用印申请"
    width="900px"
    :close-on-click-modal="false"
    :visible.sync="dialog.visible"
    @close="resetForm('dataForm')"
  >
    <!-- 添加 会议室-->
    <el-form
      :model="dataForm"
      :rules="rules"
      ref="dataForm"
      label-width="150px"
      class="demo-dataForm"
      :disabled="disabled"
    >
      <el-form-item label="经办人" prop="handlerName">
        <el-input v-model="dataForm.handlerName"></el-input>
      </el-form-item>
      <el-form-item label="日期" prop="useDate">
        <el-date-picker
          v-model="dataForm.useDate"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="用印文件说明" prop="description">
        <el-input v-model="dataForm.description"></el-input>
      </el-form-item>
      <el-form-item label="文件份数" prop="fileCount">
        <el-input-number
          v-model="dataForm.fileCount"
          :min="1"
          label="请输入文件份数"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="文件类别" prop="fileCategory">
        <el-select
          v-model="dataForm.fileCategory"
          placeholder="请选择文件类别"
          class="maxWidth"
        >
          <el-option
            v-for="item in dict.type.seal_file_type"
            :key="item.value + 'file'"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="加盖何种印章" prop="stampType">
        <el-select
          v-model="dataForm.stampType"
          placeholder="请选择加盖何种印章"
          class="maxWidth"
        >
          <el-option
            v-for="item in dict.type.seal_manage"
            :key="item.value + 'file'"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="附件" prop="attachments">
        <div>
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            multiple
            :show-file-list="false"
            :on-success="successubjectAttachments"
            :headers="headers"
          >
            <el-button size="small">
              <i class="el-icon-plus"></i>
              添加附件
            </el-button>
          </el-upload>
          <div
            v-for="(item, index) in dataForm.attachments"
            :key="index"
            style="display: flex; justify-content: space-between"
          >
            <div>
              {{ item.filename }}
            </div>
            <div
              v-if="!disabled"
              @click="onDelFile(index)"
              style="cursor: pointer; font-size: 18px"
            >
              <i class="el-icon-close"></i>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="服务费支付情况" prop="servicePayment">
        <el-input v-model="dataForm.servicePayment"></el-input>
      </el-form-item>
      <el-form-item label="审核人员" prop="reviewers">
        <template v-if="disabled">
          <div v-for="(item, index) in dataForm.reviewerList" :key="index">
            <span>{{ item.userName }}</span>
            <span>
              <dict-tag
                :options="dict.type.audit_status"
                :value="item.auditType"
              />
            </span>
          </div>
        </template>

        <el-select
          v-else
          multiple
          v-model="dataForm.reviewers"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="抄送">
        <el-select
          multiple
          v-model="dataForm.makeList"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="foot">
      <el-button type="primary" @click="submitForm('dataForm')">确定</el-button>
      <el-button @click="resetForm('dataForm')">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { list } from "@/api/system/case";
import { caselist } from "@/api/case/case";
import { applicationadd, getAllUser, applicationdetail } from "@/api/met";
import { mapState } from "vuex";
import { getToken } from "@/utils/auth";
import moment from "moment";
import { defaultList } from "@/api/case/case";
export default {
  components: {},
  dicts: ["seal_file_type", "seal_manage", "audit_status"],
  data() {
    return {
      dialog: {
        visible: false,
      },
      headers: { Authorization: "Bearer " + getToken() },
      dataForm: {},
      loading: false,
      userList: [], // 用户列表
      tree: [],
      options: [],
      type: 1, //1添加，2编辑，3查看
      rules: {
        fileCategory: [
          { required: true, message: "请选择文件类别", trigger: "change" },
        ],
        fileCount: [
          { required: true, message: "请输入文件份数", trigger: "blur" },
        ],
        servicePayment: [
          { required: true, message: "请输入服务费支付情况", trigger: "blur" },
        ],
        stampType: [
          { required: true, message: "请选择加盖何种公章", trigger: "change" },
        ],
        useDate: [{ required: true, message: "请选择日期", trigger: "change" }],
        handlerName: [
          { required: true, message: "请输入经办人", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入用印文件说明", trigger: "blur" },
        ],
        reviewers: [
          {
            required: true,
            type: "array",
            message: "请选择审核人员",
            trigger: "change",
          },
        ],
        attachments: [
          {
            required: true,
            type: "array",
            message: "请上传附件",
            trigger: "change",
          },
        ],
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      disabled: false,
    };
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.name,
      userId: (state) => state.user.id,
    }),
  },
  methods: {
    onDelFile(index) {
      this.$delete(this.dataForm.attachments, index);
    },
    successubjectAttachments(response, file, fileList) {
      //标的额证明文件
      console.log("上传成功", response, file, fileList);
      if (response.code == 200) {
        this.dataForm.attachments.push({
          filename: response.originalFilename,
          size: file.size,
          remark: "",
          createTime: moment().format("yyyy-MM-DD HH:mm:ss"),
          url: response.url,
          mimeType: file.name.split(".")[1],
        });
      } else {
        this.$message.error(response.msg);
      }
    },
    getAllUser() {
      getAllUser().then((res) => {
        this.userList = res.data;
      });
    },
    //打开弹窗
    async open(row = {}, type = 1) {
      this.disabled = type === 2;
      let detail = null;
      if (row.id) {
        console.log("--------------");
        let res = await applicationdetail(row.id);
        detail = res.data;
      } else {

      }

      list().then((res) => {
        this.dataForm = {
          fileCategory: "", // 文件类别
          fileCount: "", // 文件份数
          servicePayment: "", // 服务费支付情况
          stampType: "", // 加盖何种公章
          useDate: "", //日期
          handlerName: "", //经办人
          description: "", //用印文件说明
          attachments: [], // 附件    filename 文件名称   url文件地址  size 文件大小
          reviewers: [], // 审核人员
          makeList: [], // 抄送人员
          ...row,
          ...detail,
        };
        if (!row.id) {
          this.onSetDefault()
        }
        this.dialog.visible = true;
        this.$refs.dataForm.resetFields();
      });
    },
    // 设置默认审核人员
    onSetDefault () {
      defaultList({ type: 3 }).then(res => {
        this.dataForm.reviewers = res.data.map(v => v.userId)
      })
    },
    remoteMethod(query) {
      this.loading = true;
      caselist({ caseName: query }).then((res) => {
        this.options = res.rows;
        this.loading = false;
      });
    },
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined

          data[i].children = undefined;
        } else {
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    changecase(val) {
      console.log(val);
      console.log(this.$refs.cascader.getCheckedNodes()[0].label);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("提交成功");
          let param = { ...this.dataForm };

          param.caseId = this.dataForm.caseId;
          // param.caseName = this.$refs.cascader.getCheckedNodes()[0].label;
          param.applyBy = this.userName;
          param.applyById = this.userId;
          applicationadd(param).then((res) => {
            this.$emit("submit");
            this.resetForm(formName);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialog.visible = false;
    },
  },
  mounted() {
    this.getAllUser();
    this.remoteMethod();
  },
};
</script>

<style lang="scss" scoped>
.foot {
  text-align: center;
}
</style>
